const Koa = require('koa');
const app = new Koa();
const path = require('path');
const fs = require('fs');
const sfc = require('@vue/compiler-sfc');
const dom = require('@vue/compiler-dom');
const mimeObj = {
    html: 'text/html',
    js: 'application/javascript',
    css: 'text/css'
}

function createStyle(source) {
    return `
        const style = document.createElement('style');
        style.innerHTML = '${source.replace(/\n/g, "")}';
        document.head.appendChild(style);
    `;
}

function changeImport(source) {
    // import { sum } from './src/common.js'
    // import { createApp, h } from 'vue'
    // import { initCustomFormatter, warn } from '@vue/runtime-dom';
    const reg = /from\s*['"](.+)['"]/g;
    return source.replace(reg, ($0, $1) => {
        if ($1.startsWith('.') || $1.startsWith('/')) {
            return $0;
        } else {
            return $0.replace($1, '/@modules/'+ $1);
        }
    });
}

app.use((ctx) => {
    const {url, query} = ctx;
    const root = process.cwd();
    console.log('url', url, query, query.type, query.type === 'template');

    if (url === '/') {
        const filePath = path.resolve(root, './shuiying.html');
        const content = fs.readFileSync(filePath, 'utf-8');
        const process = `window.process = {env: 'development'}`
        ctx.type = mimeObj.html;
        // 考虑process变量
        ctx.body = content + `<script>${process}</script>`;
    } else if (url.endsWith('.js')) {
        const filePath = path.resolve(root, url.slice(1));
        const content = fs.readFileSync(filePath, 'utf-8');
        ctx.type = mimeObj.js;
        ctx.body = changeImport(content);
    } else if (/^\/@modules\/(.+)/.test(url)) {
        const pluginPackageJsonPath = path.resolve(root, `node_modules/${RegExp.$1}/package.json`);
        let pluginPackageJsonContent = fs.readFileSync(pluginPackageJsonPath, 'utf-8');
        pluginPackageJsonContent = JSON.parse(pluginPackageJsonContent);
        const filePath = path.resolve(path.dirname(pluginPackageJsonPath), pluginPackageJsonContent.module);
        const content = fs.readFileSync(filePath, 'utf-8');
        ctx.type = mimeObj.js;
        ctx.body = changeImport(content);
    } else if (url.endsWith('.css')) {
        const filePath = path.resolve(root, url.slice(1));
        const content = fs.readFileSync(filePath, 'utf-8');
        ctx.type = mimeObj.js;
        ctx.body = createStyle(content);
    } else if(url.indexOf('.vue') > -1) {
        // .vue = template + script + style
        // 用compiler-sfc转换.vue得到template + script + style
        // template => render
        // 用compiler-dom转换template
        // script => .js
        // style => .js
        const filePath = path.resolve(root, url.slice(1).split('?')[0]);
        const content = fs.readFileSync(filePath, 'utf-8');
        const {descriptor} = sfc.parse(content);
        const {script, template} = descriptor;
        // console.log('script', script);
        // console.log('template', template);
        if (query.type === 'template') {
            console.log('xinxiasdfasdfasdfasdfasdfasdfasdfasdfasdfadfasdfasdf')
            ctx.type = mimeObj.js;
            ctx.body = changeImport(dom.compile(template.content, {mode: 'module'}).code);
        } else {
            ctx.type = mimeObj.js;
            ctx.body = `
            ${changeImport(script.content.replace('export default', 'const __script = '))}
            import {render as __render} from '${url}?type=template';
            __script.render = __render;
            export default __script;
        `;
        }
    } else {
        ctx.body = '该文件，服务器未做解析';
    }
});

module.exports = app;